<template>
  <div class="p-2">
    <transition
      v-if="!executeVisiable"
      :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave"
    >
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="计划名称">
            <el-input placeholder="请输入名称" v-model="queryParams.planName" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="计划类型">
            <el-select v-model="queryParams.planType" placeholder="请选择计划类型" clearable>
              <el-option label="日计划" :value="0"></el-option>
              <el-option label="周计划" :value="1"></el-option>
              <el-option label="月计划" :value="2"></el-option>
              <el-option label="无计划" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="巡检路线">
            <el-select v-model="queryParams.routeId" placeholder="请选择巡检路线" clearable>
              <el-option v-for="item in inspectionrouteOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="启用状态">
            <el-select v-model="queryParams.enableStatus" placeholder="请选择" clearable>
              <el-option label="正常启用" value="0"></el-option>
              <el-option label="暂停使用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never" v-if="!executeVisiable">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:studentRecognitionRecord:add']">新增</el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:studentRecognitionRecord:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['attendance:studentRecognitionRecord:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Document"
              :disabled="ids.length!==1"
              @click="handleExecute()"
              v-hasPermi="['attendance:studentRecognitionRecord:remove']"
              >执行</el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:studentRecognitionRecord:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 360px)"
        v-loading="loading"
        :data="inspectionplanSettingList"
        @selection-change="handleSelectionChange"
        :row-key="(row) => row.itemsId "
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划编号" align="center" prop="planId" />
        <el-table-column label="计划名称" align="center" prop="planName" />
        <el-table-column label="启用状态" align="center" prop="enableStatus">
          <template #default="scope">
            <span v-if="scope.row.enableStatus==0"> 正常启用 </span>
            <span v-if="scope.row.enableStatus==1"> 暂停使用 </span>
          </template>
        </el-table-column>
        <el-table-column label="计划类型" align="center" prop="planType">
          <template #default="scope">
            <span v-if="scope.row.planType==0"> 日计划 </span>
            <span v-if="scope.row.planType==1"> 周计划 </span>
            <span v-if="scope.row.planType==2"> 月计划 </span>
            <span v-if="scope.row.planType==3"> 无计划 </span>
          </template>
        </el-table-column>
        <el-table-column label="巡检路线" align="center" prop="routeId">
          <template #default="scope">
            <span v-for="item in inspectionrouteOptions" :key="item.routeId">
              <span v-if="scope.row.routeId==item.routeId">{{ item.routeName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" align="center" prop="startDate" />
        <el-table-column label="备注" align="center" prop="duration" />
        <el-table-column label="最后修改人" align="center" prop="updateByName" />
        <el-table-column label="最后修改时间" align="center" prop="studentStatus" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['attendance:group:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['attendance:group:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-card shadow="never" v-if="executeVisiable">
      <template #header>
        <div class="card-header">
          <span> <el-button type="primary" :icon="Back" @click="executeVisiable = false">返回</el-button></span>
        </div>
      </template>
      <execute :visible="executeVisiable" :todolist="todolist" :id="ids[0]" @closeDialog="closeExecuteDialog" />
    </el-card>
    <!-- 添加或修改学生识别记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1100px" append-to-body>
      <el-form ref="studentRecognitionRecordFormRef" label-width="auto" :inline="true" :model="form" :rules="rules">
        <el-row>
          <el-col :span="9">
            <el-form-item label="计划名称:" prop="planName" style="width: 100%;">
              <el-input v-model="form.planName" style="width: 80%;" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="巡检路线:" prop="routeId">
              <el-select v-model="form.routeId" placeholder="请选择巡检路线">
                <el-option v-for="item in inspectionrouteOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="enableStatus">
              <el-radio-group v-model="form.enableStatus">
                <el-radio label="0">正常启用</el-radio>
                <el-radio label="1">暂停使用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="按顺序巡检:" prop="isOrder">
              <el-select v-model="form.isOrder" placeholder="请选择">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="开始日期-结束日期:" label-width="180" />
          </el-col>
          <el-col :span="4">
            <el-form-item label="" label-width="80" prop="startDate" style="margin-right: 0px;">
              <el-date-picker style="width: 150px;" v-model="form.startDate" type="date" />
              <span style="text-align: center;width: 27px;">~</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" label-width="0" prop="endDate">
              <el-date-picker style="width: 150px;" v-model="form.endDate" type="date" />&emsp;为空时,永不结束
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划类型:" prop="planType">
              <el-select v-model="form.planType" placeholder="请选择" style="width: 100%;" @change="planTypeChange">
                <el-option label="日计划" value="0"></el-option>
                <el-option label="周计划" value="1"></el-option>
                <el-option label="月计划" value="2"></el-option>
                <el-option label="无计划" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.planType !== '3'">
            <el-form-item label-width="90" label="执行间隔:" prop="executeInterval">
              每 &emsp;<el-input-number style="width: 60px;" v-model="form.executeInterval" :controls="false" /> &emsp;
              {{ form.planType === '0' ? '天' : form.planType === '1' ?  '周' : form.planType === '2' ? '月' : '' }}
            </el-form-item>
          </el-col>
          <!-- 周计划 -->
          <el-col :span="12" v-if="form.planType === '1'">
            <el-form-item label-width="80" label="" prop="executeCycle">
              <el-checkbox-group v-model="form.executeCycle">
                <el-checkbox label="1">星期一</el-checkbox>
                <el-checkbox label="2">星期二</el-checkbox>
                <el-checkbox label="3">星期三</el-checkbox>
                <el-checkbox label="4">星期四</el-checkbox>
                <el-checkbox label="5">星期五</el-checkbox>
                <el-checkbox label="6">星期六</el-checkbox>
                <el-checkbox label="7">星期日</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <!-- 月计划 -->
          <el-col :span="12" v-if="form.planType == '2'" style="display: flex;justify-content: space-between;">
            <div>
              <el-radio v-model="form.monthType" :label="0" style="margin-right: 10px;">第：</el-radio>
              <el-input-number v-model="form.monthDay" :controls="false" style="width: 50px;" />
              &emsp;天&emsp;
            </div>
            <div>
              <el-radio v-model="form.monthType" :label="1" style="margin-right: 10px;">在：</el-radio>
              <el-select v-model="form.monthWeek" style="width: 100px;" placeholder="请选择">
                <el-option label="第一个" value="1"></el-option>
                <el-option label="第二个" value="2"></el-option>
                <el-option label="第三个" value="3"></el-option>
                <el-option label="第四个" value="4"></el-option>
              </el-select>
              <span>&emsp;&emsp;周几：&emsp;</span>
              <el-select v-model="form.monthDayOfWeek" style="width: 100px;" placeholder="请选择">
                <el-option label="星期一" value="1" />
                <el-option label="星期二" value="2" />
                <el-option label="星期三" value="3" />
                <el-option label="星期四" value="4" />
                <el-option label="星期五" value="5" />
                <el-option label="星期六" value="6" />
                <el-option label="星期日" value="7" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="7" v-if="form.planType !== '3'">
            <el-form-item label-width="80" label="每天评率:" prop="frequency">
              执行 &emsp;
              <el-radio-group v-model="form.frequency">
                <el-radio label="0">一次</el-radio>
                <el-radio label="1">多次</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <!-- to do 后期改成树结构 -->
            <el-form-item label-width="90" label="巡检人员:" prop="xjUserIds">
              <el-select v-model="form.xjUserIds" placeholder="请选择" multiple>
                <el-option
                  v-for="item in todolist"
                  :key="item.userId"
                  :label="item?.dept?(item?.dept?.deptName+'--'+item.nickName):item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.planType !== '3'">
            <el-form-item label="时间:" prop="xjTime">
              <el-time-picker value-format="HH:mm:ss" v-model="form.xjTime" style="width: 130px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.planType !== '3'">
            <el-form-item label="工作时长(分钟):" prop="duration">
              <el-input-number v-model="form.duration" :controls="false" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.planType !== '3'">
            <el-form-item label="允许误差(分钟):" prop="allowError">
              <el-input-number v-model="form.allowError" :controls="false" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="form.planType !== '3'">
            <el-form-item label="最少间隔(分钟):" prop="leastInterval">
              <el-input-number v-model="form.leastInterval" :controls="false" />
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="form.planType !== '3'">
            <el-form-item label="计划执行提醒:" prop="remindTimeAgo">
              开始前 &emsp;<el-input-number controls-position="right" style="width: 100px;" v-model="form.remindTimeAgo" /> &emsp;提醒即将开始
            </el-form-item>
          </el-col>
          <el-col :span="7" v-if="form.planType !== '3'">
            <el-form-item label="" prop="remindTimeAfter">
              开始后 &emsp;<el-input-number controls-position="right" style="width: 100px;" v-model="form.remindTimeAfter" /> &emsp;提醒未按时开始
            </el-form-item>
          </el-col>
          <el-col :span="7" v-if="form.planType !== '3'">
            <el-form-item label="" prop="finishTimeAfter">
              结束后 &emsp;<el-input-number controls-position="right" style="width: 100px;" v-model="form.finishTimeAfter" /> &emsp;提醒漏检情况
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重复上报:" prop="reportingStatus">
              <el-select v-model="form.reportingStatus" placeholder="请选择级别">
                <el-option label="允许重复上报" value="0"></el-option>
                <el-option label="不允许重复" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检记录提醒:" prop="recordRemind">
              <el-select v-model="form.recordRemind" placeholder="请选择级别">
                <el-option label="有记录就提醒" value="0"></el-option>
                <el-option label="不合格才提醒" value="1"></el-option>
                <el-option label="始终不提醒" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="额外巡检人员:" prop="ewUserIds">
              <el-select v-model="form.ewUserIds" placeholder="请选择" multiple>
                <el-option
                  v-for="item in todolist"
                  :key="item.userId"
                  :label="item?.dept?(item?.dept?.deptName+'--'+item.nickName):item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="检查项目来源:" prop="inspectSource">
              <el-select v-model="form.inspectSource" placeholder="请选择级别">
                <el-option label="巡检点" value="0"></el-option>
                <el-option label="巡检计划" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.inspectSource === '1'">
            <el-form-item label="检查项目" prop="items">
              <div>
                <el-button type="primary" :icon="Plus" size="small" @click="onClickAdd">添加</el-button>
                <el-button type="danger" :icon="Delete" size="small" @click="onClickDelete" :disabled="selectData.length === 0">删除</el-button>
                <div class="row-grid attrs-table">
                  <div class="row-grid-header">
                    <div class="row-grid-tr">
                      <div class="row-grid-td serial">序号</div>
                      <div class="row-grid-td name1">
                        <el-checkbox style="margin-left: 10px;" v-model="checkAll" @change="onChangeCheckBoxAll"></el-checkbox>
                      </div>
                      <div class="row-grid-td namemax row-grid-center">检查项目名称</div>
                      <div class="row-grid-td name1">抽奖概率（%）</div>
                      <div class="row-grid-td name1">类型</div>
                      <div class="row-grid-td name1">必填</div>
                      <div class="row-grid-td name1">得分</div>
                    </div>
                  </div>
                  <draggable
                    class="row-grid--draggable"
                    v-model="selectData"
                    chosenClass="row-grid-tr--chosen"
                    ghostClass="row-grid-tr--ghost"
                    dragClass="row-grid-tr--drag"
                    :forceFallback="true"
                    :item-key="(item: any) => item.routeId"
                    handle=".serial"
                    @start="true"
                    @end="draggerEnd"
                  >
                    <template #item="{ element, index }">
                      <div class="row-grid-tr">
                        <div class="row-grid-td serial">
                          <el-icon>
                            <Sort />
                          </el-icon>
                          {{ index + 1 }}
                        </div>
                        <div class="row-grid-td name1">
                          <el-checkbox v-model="element.checked"></el-checkbox>
                        </div>
                        <div class="row-grid-td namemax">
                          {{element.itemsName}}
                        </div>
                        <div class="row-grid-td name1">
                          <el-input-number
                            size="small"
                            :controls="false"
                            :precision="0"
                            :max="100"
                            :min="0"
                            style="width: 50px;"
                            v-model="element.chance"
                            type="number"
                          ></el-input-number>
                        </div>
                        <div class="row-grid-td name1">
                          {{typeArr[element.itemsType]}}
                        </div>
                        <div class="row-grid-td name1">
                          {{element.isRequired === '0' ? '否' : '是'}}
                        </div>
                        <div class="row-grid-td name1">
                          {{element.isScore === '0' ? '否' : '是'}}
                        </div>
                      </div>
                    </template>
                  </draggable>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="display: flex; align-items: center;justify-content: space-between;">
          <div>{{getTipStr()}}</div>
          <div>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <addCheck :visible="addCheckVisiable" @closeDialog="closeAddCheckDialog" @getSelectData="getSelectData" />
  </div>
</template>

<script setup name="InspectionplanSetting" lang="ts">
import { inspectionplanPageQuery, inspectionplanForm } from '@/api/inspection/inspectionplanSetting/types';
import {
  ApiGetInspectionplanSettingList, ApiCreateInspectionplan, ApiUpdateInspectionplan, ApiDeleteInspectionPlan, ApiGetInspectionPlanDetail
} from '@/api/inspection/inspectionplanSetting';
import { userlist } from '@/api/inspection'
import { ApiGetInspectionRouteList } from '@/api/inspection/inspectionroute';
import { Delete, Plus } from '@element-plus/icons-vue';
import addCheck from '@/views/Inspection/ports/setting/childrens/addCheck.vue';
import draggable from 'vuedraggable';
import execute from '@/views/Inspection/Inspectionplan/setting/childrens/execute.vue';
import { Back } from '@element-plus/icons-vue'


const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const inspectionplanSettingList = ref<inspectionplanPageQuery[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const ids = ref<string | number []>([]);
const total = ref(0);
const dateRangeRecognizeTime = ref<[DateModelType, DateModelType]>(['', '']);
const inspectionrouteOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const studentRecognitionRecordFormRef = ref<ElFormInstance>();
const addCheckVisiable = ref(false);
const selectData: any = ref([]);
const checkAll = ref(false);
const executeVisiable = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const typeArr = [
   '选择项',
   '数字项',
   '文本项',
   '拍照项',
]
const initFormData: inspectionplanForm = {
 planName: '',
 routeId: '',
 enableStatus: '0',
 comparisonScore: NaN,
 startDate: new Date(),
 endDate: '',
 planType: '',
 frequency: '0',
 monthType: 0,
 executeInterval: 1,
 monthDay: NaN,
 monthWeek: '',
 monthDayOfWeek: '',
 xjUserIds: [],
 executeCycle: [],
 xjTime: '',
 userId: '',
 duration: 60,
 allowError: 0,
 leastInterval: 0,
 remindTimeAgo: 10,
 remindTimeAfter: 10,
 finishTimeAfter: 10,
 reportingStatus: '1',
 recordRemind: '1',
 ewUserIds: '',
 inspectSource: '0',


};
const data = reactive<PageData<inspectionplanForm, inspectionplanPageQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planName: '',
    routeId: '',
    enableStatus: '',
  },
  rules: {
    planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
  }
});

const { queryParams, form, rules } = toRefs(data);

const getInspectionrouteOptions = async () => {
  const res = await ApiGetInspectionRouteList({pageNum: 1, pageSize: 999});
  inspectionrouteOptions.value = res.rows;
}

const todolist=ref<any>([])
/** 查询执行人列表 */
const gettodoList = async () => {
  loading.value = true;
  const res = await userlist({});
  todolist.value = res.rows;
  // total.value = res.total;
  loading.value = false;
};

const getClassTree = async () => {
  // const res = await classTree();
  // classOptions.value = res.data;
};

// 计划类型change
const planTypeChange = (e: string) => {
  console.log(e, 'e')
}

/** 查询学生识别记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await ApiGetInspectionplanSettingList(queryParams.value);
  inspectionplanSettingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};const getTipStr = () => {
  const weekName = ['', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
  const theWeek =['', '第一周', '第二周', '第三周', '第四周'];
  let weekStr = ' ';
  // 判断是字符串还是数组
  if (form.value.executeCycle !== '' && typeof form.value.executeCycle === 'string') {
    weekStr = (form.value.executeCycle as string).split(',').map((item: string) => {
        return weekName[Number(item)]
      }).join(',')
    } else if (form.value.executeCycle !== '' && typeof form.value.executeCycle === 'object') {
      weekStr = (form.value.executeCycle as string[]).map((item: string) => {
        return weekName[Number(item)]
      }).join(',')
    }
  let timeStr= ' ';
  if (form.value.xjTime!=='' && typeof form.value.xjTime === 'string') {
    timeStr = form.value.xjTime
  } else {
    timeStr = proxy?.parseTime(form.value.xjTime, '{h}:{i}:{s}') || ''
  }
  let startDate = ' ';
  if (form.value.startDate!=='' && typeof form.value.startDate === 'string') {
    startDate = form.value.startDate
  } else {
    startDate = proxy?.parseTime(form.value.startDate, '{y}-{m}-{d}') || ''
  }
  let monthStr = ' ';
  if (form.value.monthType === 0) {
    monthStr = `每${form.value.executeInterval ? form.value.executeInterval : '  '}个月，在当月第${form.value.monthDay ? form.value.monthDay : '  '}天的${timeStr}执行，从${startDate}开始使用计划`
  } else {
    monthStr = `每${form.value.executeInterval ? form.value.executeInterval : '  '}个月，在当月的${form.value.monthWeek? theWeek[Number(form.value.monthWeek)]: ' '}${form.value.monthDayOfWeek ? weekName[Number(form.value.monthDayOfWeek)]: '  '}${timeStr}执行，从${startDate}开始使用计划`
  }
  switch (form.value.planType) {
    case '0':
      return `每${form.value.executeInterval ? form.value.executeInterval : '  '}天的${timeStr}执行，从${startDate}开始使用计划`
    case '1':
      return `每${form.value.executeInterval ? form.value.executeInterval : '  '}周的${weekStr}的${timeStr}，从${startDate}开始使用计划`
    case '2':
      return monthStr
    case '3':
      return '无时间限定，24小时均可执行，不计算漏检统计'
    default:
      break;
  }
 return ''
}
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentRecognitionRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeRecognizeTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
const selectArr=ref<any[]>([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.planId);
  single.value = selection.length != 1;
  console.log("dddddd",selection)
  selectArr.value=selection
  multiple.value = !selection.length;
};

const handleExecute = () => {
  if(ids.value.length==1){
       if(selectArr.value[0]?.planType=="3"){
        return ElMessage.warning('无计划类型不能执行');
       }
       executeVisiable.value = true;
  }

}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加巡检计划';
  console.log(form.value, 'form')
};

/** 修改按钮操作 */
const handleUpdate = async (row?: inspectionplanForm) => {
  reset();
  const _id = row?.planId || ids.value[0];
  const res = await ApiGetInspectionPlanDetail(_id);
  Object.assign(form.value, res.data);
  form.value.executeCycle = res.data?.executeCycle?.split(',') || [];
  selectData.value = res.data.planItems || [];
  dialog.visible = true;
  dialog.title = '修改计划';
};

/** 提交按钮 */
const submitForm = () => {
  console.log(form.value, '------')
  studentRecognitionRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {

    const params = JSON.parse(JSON.stringify(form.value));
    params.startDate = proxy?.parseTime(form.value.startDate, '{y}-{m}-{d}');
    params.endDate = proxy?.parseTime(form.value.endDate, '{y}-{m}-{d}');
    params.ewUserIds = params.ewUserIds.length > 0 ? params.ewUserIds.join(','): '';
    params.xjUserIds = params.xjUserIds.join(',');
    if (typeof params.executeCycle === 'object') {
      params.executeCycle = params.executeCycle.join(',');
    }
    // params.xjTime =  proxy?.parseTime(form.value.xjTime, '{y}-{m}-{d} {h}:{i}:{s}');
    params.appSource =  0;
      buttonLoading.value = true;
      if (form.value.planId) {
        const items =  JSON.parse(JSON.stringify(selectData.value)).map((item: { itemsName: string; itemsId: string; chance: string; id:string }) => {
          return {
            id: item.id,
            planId: null,
            itemsId: item.itemsId,
            chance: item.chance || 0,
          };
        });
        params.xjPlanItemsList = items
        await ApiUpdateInspectionplan(params).finally(() => (buttonLoading.value = false));
      } else {
        const items =  JSON.parse(JSON.stringify(selectData.value)).map((item: { itemsName: string; itemsId: string; chance: string }) => {
          return {
            id: null,
            planId: null,
            itemsId: item.itemsId,
            chance: item.chance || 0,
          };
        });
        params.xjPlanItemsList = items
        await ApiCreateInspectionplan(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: inspectionplanForm) => {
  if(!row){
    console.log("ddddddd",ids.value[0])
  await proxy?.$modal.confirm('是否确认删除选中的"' + ids?.value?.length + '"条数据？').finally(() => (loading.value = false));
  await ApiDeleteInspectionPlan(ids.value);
  proxy?.$modal.msgSuccess('删除成功');
  }else{
    const _ids = row?.planId;
    let msg = inspectionplanSettingList.value.find((e:any) => _ids === e.itemsId)?.planName;
    await proxy?.$modal.confirm('是否确认删除选中的"' + msg + '"数据？').finally(() => (loading.value = false));
   await ApiDeleteInspectionPlan(_ids);
   proxy?.$modal.msgSuccess('删除成功');
  }
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/studentRecognitionRecord/export',
    {
      ...queryParams.value
    },
    `studentRecognitionRecord_${new Date().getTime()}.xlsx`
  );
};


const onChangeCheckBoxAll = (val: any) => {
  console.log(val, 'val')
  if (val) {
    selectData.value = selectData.value.map((item: any) => {
      item.checked = true;
      return item;
    })
  } else {
    selectData.value = selectData.value.map((item: any) => {
      item.checked = false;
      return item;
    })
  }
}

const closeExecuteDialog = () => {
  executeVisiable.value = false;
}

const closeAddCheckDialog = () => {
  addCheckVisiable.value = false;
};

const getSelectData = (data: any) => {
  selectData.value = [...selectData.value, ...data];
  console.log(selectData.value, 'tableData');
  addCheckVisiable.value = false;
};

const onClickAdd = () => {
  addCheckVisiable.value = true;
};

const onClickDelete = () => {
  console.log(selectData.value, 'selectData');
  if (!selectData.value.some((item: any) => item.checked === true)) {
    return ElMessage.error('请选择要删除的项');
  }
  // 判断selectData中是否有checked的 或者 checked为true
  selectData.value = JSON.parse(JSON.stringify(selectData.value.filter((item: any, index: number) => !(item.checked || false))));
  console.log('删除后：', selectData.value);
};

//拖拽结束事件
const draggerEnd = (v: any) => {
  //
}

onMounted(() => {
  gettodoList();
  getClassTree();
  getInspectionrouteOptions();
  getList();
});
</script>
<style lang="scss" scoped>

@import '@/assets/styles/variables.module';
$--border-color-lighter: #edf0f5;
$--background-color-base: #f6f6f6;
$--color-text-regular: #646666;
.row-grid {
  position: relative;
  width: 100%;
  font-size: 14px;
  overflow: hidden;
  margin-top: 20px;
  margin-bottom: 10px;
  border: 1px solid $--border-color-lighter;
  border-radius: 10px;
  background-color: #fff;

  &-header {
    background-color: $--background-color-base;
  }

  &-tr {
    display: flex;
    align-items: center;
    width: 100%;

    & + .row-grid-tr {
      border-top: 1px solid $--border-color-lighter;
    }

    &--chosen {
      cursor: move;
    }

    &--ghost {
      opacity: .5;
      background-color: #f6f8fa;
    }
  }

  &-th, &-td {
    padding: 10px 16px;
    flex: auto;
    color: $--color-text-regular;
    line-height: 1.5
  }

  &-footer {
    border-top: 1px solid $--border-color-lighter;
  }

  &-empty {
    padding: 16px;
    text-align: center;
    color: $--color-text-regular;
  }

  &-right {
    text-align: right;
  }

  &-center {
    text-align: center;
  }

  &--bordered {
    .row-grid-th,
    .row-grid-td {
      & + .row-grid-th,
      & + .row-grid-td {
        border-left: 1px solid $--border-color-lighter;
      }
    }
  }
}

.attrs-table {
  width: 740px;
  line-height: 20px;
  border: 1px solid #edf0f5;

  .row-grid--draggable {
    :deep(.el-form-item__content) {
      justify-content: space-around;
    }
    .row-grid-tr {
      .serial {
        cursor: grab;
      }

      &--chosen {
        .serial {
          cursor: move;
        }
      }

      &--ghost {
        opacity: 0.1;
      }

      &--drag {
        border-bottom: 1px solid #edf0f5;
        background-color: #fff;
      }
    }
  }

  .row-grid-td {
    width: 160px;
    white-space: nowrap;

    &.serial {
      width: 40px;
      text-align: left;
      .sort {
        position: relative;
        color: #969999;
        vertical-align: middle;
        margin: 0 4px 0 -4px;
      }
    }

    &.name1 {
      width: 100px;
      text-align: center;
    }

    &.namemax {
      width: 300px;
      text-align: center;
    }

    &.action {
      width: 70px;
    }

    & + .row-grid-td {
      padding-left: 0;
    }
  }
}
</style>
